var async = require("async")
var util = require("../../../util/util.js")
var robots = require("../../../conf/robot.json")
module.exports = function(app) {
	return new DBRemote(app);
};

var DBRemote = function(app) {
	this.app = app
	DBRemote.app = app
    DBRemote.dbService = this.app.get("dbService")
    DBRemote.channelService = this.app.get('channelService')
    if(DBRemote.dbService && DBRemote.dbService.db){
    	DBRemote.db = DBRemote.dbService.db
    }
}

var local = {}

//每日0点刷新方法
local.everydayRefresh = function(){
	console.log("local.everydayRefresh : "+(new Date()).toString())
	DBRemote.dbService.db.del("game:redTask:received")
	local.dayOnlineUpdate()
	local.runQuicklyFun()
	local.answerFun()
	local.dayClearRoom()
}
//每日21点刷新方法
local.everyday21Refresh = function(){

}
//获取账号信息
DBRemote.prototype.getAccountInfo = function(uid,cb) {
	var info = {
		balance : 0,
		freezeBalance : 0,
		NoAdTime : 0
	}
	async.waterfall([
		function(next) {
			DBRemote.dbService.db.hget("NoAdTimeList",uid,function(err,data) {
				if(!err && data){
					info.NoAdTime = data
				}
				next()
			})
		},
		function(next) {
			DBRemote.dbService.getItem(uid,103,function(data) {
				if(data){
					info.balance = data
				}
				next()
			})
		},
		function(next) {
			DBRemote.dbService.getItem(uid,104,function(data) {
				if(data){
					info.freezeBalance = data
				}
				next()
			})
		},
		function() {
			cb(true,info)
		}
	],function(err) {
		console.log(err)
	})
}
//获取跑得快比赛场数据
DBRemote.prototype.getRunCHistory = function(uid,cb) {
	DBRemote.dbService.db.hgetall("game:competition:history:"+uid,function(err,data) {
		if(!err && data){
			cb(true,data)
		}else{
			cb(true,{})
		}
	})
}
//比赛场参与次数
DBRemote.prototype.setRunCPlay = function(uid,cid,score,cb) {
	DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"allCount:"+cid,1,function() {})
	DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"allScore",score,function() {})
	cb()
}
//比赛场夺冠
DBRemote.prototype.setRunCChampion = function(uid,cid,itemId,value,cb) {
	// console.log("setRunCWin",uid,cid,award)
	DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"championCount:"+cid,1,function() {})
	DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"allChampionCount",1,function() {})
	if(itemId && value){
		DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"awardItem:"+itemId,value,function() {})
	}
	cb()
}
//比赛场亚军
DBRemote.prototype.setRunCSecond = function(uid,cid,itemId,value,cb) {
	// console.log("setRunCWin",uid,cid,award)
	DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"secondCount:"+cid,1,function() {})
	DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"allSecondCount",1,function() {})
	if(itemId && value){
		DBRemote.dbService.db.hincrby("game:competition:history:"+uid,"awardItem:"+itemId,value,function() {})
	}
	cb()
}
//获取答题游戏数据
DBRemote.prototype.getAnswerInfo = function(uid,cb) {
	var info = {
		allSuccessNumber : 0,
		playCount : 0,
		success : 0,
		resurgenceCount : 0,
		allBonus : 0
	}
	async.waterfall([
		function(next) {
			//获取今日总奖金
			DBRemote.dbService.db.get("game:award:answer:allBonus",function(err,data) {
				if(err || !data){
					info.allBonus = 0
				}else{
					info.allBonus = data
				}
				next()
			})
		},
		function(next) {
			//获取总完成人数
			DBRemote.dbService.db.get("game:answer:allSuccessNumber",function(err,data) {
				if(err || !data){
					info.allSuccessNumber = 0
				}else{
					info.allSuccessNumber = data
				}
				next()
			})
		},
		function(next) {
			//获取参与次数
			DBRemote.dbService.db.hget("game:answer:playCount",uid,function(err,data) {
				if(err || !data){
					info.playCount = 0
				}else{
					info.playCount = data
				}
				next()
			})
		},
		function(next) {
			//获取完成次数
			DBRemote.dbService.db.hget("game:answer:success",uid,function(err,data) {
				if(err || !data){
					info.success = 0
				}else{
					info.success = data
				}
				next()
			})
		},
		function(next) {
			//获取复活次数
			DBRemote.dbService.db.hget("game:answer:resurgenceCount",uid,function(err,data) {
				if(err || !data){
					info.resurgenceCount = 0
				}else{
					info.resurgenceCount = data
				}
				cb(true,info)
			})
		}
	],function(err) {
		console.log(err)
	})
}
//获取答题游戏历史记录
DBRemote.prototype.getAnswerHistory = function(dayStr,cb) {
	var info = {
		allBonus : 0,
		oneBonus : 0,
		allPlayer : 0
	}
	DBRemote.dbService.db.hmget("game:answer:history:"+dayStr,["allBonus","oneBonus","allPlayer"],function(err,data) {
		if(!err && data){
			info.allBonus = data[0]
			info.oneBonus = data[1]
			info.allPlayer = data[2]
		}
		cb(true,info)
	})
}
//开启定时器
DBRemote.prototype.runRefresh = function(cb) {
	var curTime = new Date()
	//每日零时刷新
	var endTime = new Date()
	endTime.setDate(endTime.getDate() + 1)
	endTime.setHours(0)
	endTime.setMinutes(0)
	endTime.setSeconds(0)
	endTime.setMilliseconds(0)
	var tmpTime = endTime.getTime() - curTime.getTime()
	setTimeout(function() {
		local.everydayRefresh()
		setInterval(local.everydayRefresh,24 * 60 * 60 * 1000 + 10000)
	},tmpTime)
	//每日21点刷新
	endTime = new Date()
	if(endTime.getHours() >= 21){
		endTime.setDate(endTime.getDate() + 1)
	}
	endTime.setMinutes(0)
	endTime.setSeconds(0)
	endTime.setMilliseconds(0)
	endTime.setHours(21)
	var tmpTime = endTime.getTime() - curTime.getTime()
	setTimeout(function() {
		local.everyday21Refresh()
		setInterval(local.everyday21Refresh,24 * 60 * 60 * 1000 + 10000)
	},tmpTime)
	//开启缓存数据库
	DBRemote.dbService.beginCacheDB()
	cb(true)
}
//答题游戏处理
local.answerFun = function() {
	var allBonus = 0 				//总奖金
	var oneBonus = 0 				//单份奖金
	var allPlayer = 0 				//总完成人数
	var playrList = {} 				//完成人数列表
	async.waterfall([
		function(next) {
			//获取总奖金
			DBRemote.dbService.db.get("game:award:checkpoint:allBonus",function(err,data) {
				if(err || !data){
					allBonus = 0
				}else{
					allBonus = parseInt(data)
				}
				next()
			})
		},
		function(next) {
			//获取总完成人数
			DBRemote.dbService.db.get("game:answer:allSuccessNumber",function(err,data) {
				if(err || !data){
					allPlayer = 0
				}else{
					allPlayer = parseInt(data)
				}
				next()
			})
		},
		function(next) {
			//获取完成人数列表
			DBRemote.dbService.db.hgetall("game:answer:success",function(err,data) {
				if(err || !data){
					playrList = 0
				}else{
					playrList = data
				}
				next()
			})
		},
		function(next) {
			//答题游戏根据每日完成人数发放奖励
			console.log("allBonus : ")
			console.log(allBonus)
			console.log("allPlayer : ")
			console.log(allPlayer)
			console.log("playrList : ")
			console.log(playrList)
			if(allPlayer){
				oneBonus = Math.floor((allBonus / allPlayer) * 100) / 100
				console.log("oneBonus : "+oneBonus)
				for(var i in playrList){
					console.log("i : "+i)
					if(playrList[i] && parseInt(playrList[i]) > 0){
						DBRemote.dbService.addItem(i,103,oneBonus,function(){})
					}
				}
				//保存历史记录
				var dayStr = util.getDateString()
				var info = {
					allBonus : allBonus,
					oneBonus : oneBonus,
					allPlayer : allPlayer,
					playrList : JSON.stringify(playrList)
				}
				DBRemote.dbService.db.hmset("game:answer:history:"+dayStr,info)
			}
			next()
		},
		function() {
			//答题游戏删除参与次数、复活次数、成功人数表、完成人数
			DBRemote.dbService.db.del("game:answer:playCount")
			DBRemote.dbService.db.del("game:answer:success")
			DBRemote.dbService.db.del("game:answer:allSuccessNumber")
			DBRemote.dbService.db.del("game:answer:resurgenceCount")
		}
	],function(err) {
		console.log(err)
	})
}
//跑得快游戏处理
local.runQuicklyFun = function() {
	var allBonus = 0 				//总奖金
	var awardType = 101 			//奖金类型
	var oneBonus = 0 				//单份奖金
	var allPlayer = 0 				//总完成人数
	var playrList = {} 				//完成人数列表
	async.waterfall([
		function(next) {
			//获取总奖金
			DBRemote.dbService.db.get("game:award:checkpoint:allBonus",function(err,data) {
				if(err || !data){
					allBonus = 0
				}else{
					allBonus = parseInt(data)
				}
				next()
			})
		},
		function(next) {
			//获取奖励类型
			DBRemote.dbService.db.get("game:award:checkpoint:awardType",function(err,data) {
				if(err || !data){
					awardType = 101
				}else{
					awardType = parseInt(data)
				}
				next()
			})
		},
		function(next) {
			//获取总完成人数
			DBRemote.dbService.db.get("game:checkpoint:allSuccessNumber",function(err,data) {
				if(err || !data){
					allPlayer = 0
				}else{
					allPlayer = parseInt(data)
				}
				next()
			})
		},
		function(next) {
			//获取机器人完成配置
			DBRemote.dbService.db.hget("game:hunanRunQuickly:checkpointRobots",100,function(err,data) {
				if(!err && data){
					allPlayer += parseInt(data)
				}
				next()
			})
		},
		function(next) {
			//获取完成人数列表
			DBRemote.dbService.db.hgetall("game:checkpoint:success",function(err,data) {
				if(err || !data){
					playrList = {}
				}else{
					playrList = data
				}
				next()
			})
		},
		function(next) {
			//根据每日完成人数发放奖励
			console.log("allBonus : ")
			console.log(allBonus)
			console.log("allPlayer : ")
			console.log(allPlayer)
			console.log("playrList : ")
			console.log(playrList)
			console.log("awardType : ")
			console.log(awardType)
			if(allPlayer){
				oneBonus = allBonus / allPlayer
				oneBonus = parseFloat(oneBonus.toFixed(2))
				console.log("oneBonus : "+oneBonus)
				for(var i in playrList){
					console.log("i : "+i)
					if(playrList[i] && parseInt(playrList[i]) > 0){
						DBRemote.app.rpc.db.mail.sendMail(null,i,"闯关完成奖励","恭喜您成功完成挑战。昨日总奖金"+allBonus+"元,共"+allPlayer+"人闯关完成。您获得了"+oneBonus+"元现金红包奖励，已存入个人账号，今天继续加油哦！",false,null)
						DBRemote.dbService.addItemReason(i,awardType,oneBonus,"闯关",function(){})
					}
				}
				//保存历史记录
				var dayStr = util.getDateString()
				var info = {
					allBonus : allBonus,
					oneBonus : oneBonus,
					allPlayer : allPlayer,
					playrList : JSON.stringify(playrList)
				}
				DBRemote.dbService.db.hmset("game:checkpoint:history:"+dayStr,info)
				//通知所有玩家
				DBRemote.channelService.broadcast("connector","onNotify",{"type":"runQuicklyAward","oneBonus" : oneBonus,"allPlayer" : allPlayer})
				//后台记录
			    var messageInfo = {
			    	messageType : "checkpointAward",
					allBonus : allBonus,
					oneBonus : oneBonus,
					allPlayer : allPlayer,
					playrList : playrList,
					awardType : awardType,
					time : (new Date()).getTime()
			    }
			    DBRemote.dbService.writeMessage(JSON.stringify(messageInfo))
			}
			next()
		},
		function() {
			//清除每日闯关数据
			DBRemote.dbService.db.del("game:checkpoint:winCount")
			DBRemote.dbService.db.del("game:checkpoint:success")
			DBRemote.dbService.db.del("game:checkpoint:allSuccessNumber")
			DBRemote.dbService.db.del("game:checkpoint:playCount")
			DBRemote.dbService.db.del("game:checkpoint:score")
			DBRemote.dbService.db.del("game:checkpoint:winscore")
			DBRemote.dbService.db.del("game:checkpoint:checkpointRed")
			//机器人数量更新
			DBRemote.dbService.db.hgetall("game:hunanRunQuickly:checkpointDefault",function(err,data) {
				if(!err && data){
					var info = {}
					for(var i in data){
						info[i] = Math.floor((Math.random() * 0.4 + 0.8) * parseInt(data[i]))
						if(info[parseInt(i) - 1] && info[parseInt(i) - 1] < info[i]){
							info[parseInt(i) - 1] = info[i] + 1
						}
					}
					DBRemote.dbService.db.hmset("game:hunanRunQuickly:checkpointRobots",info)
				}
			})
			//机器人信息更新
			var info = {}
			for(var i = 0;i < 20;i++){
				var uid = Math.floor(Math.random() * 1000)
				var tmpObj = {
					uid : uid,
					score : Math.floor(Math.random() * 100) + 100,
					head : robots[uid].head,
					nickname : robots[uid].nickname
				}
				info[i] = JSON.stringify(tmpObj)
			}
			DBRemote.dbService.db.hmset("game:hunanRunQuickly:checkpointRobotsInfo",info)
		}
	],function(err) {
		console.log(err)
	})
}
//每日刷新任务
local.dayOnlineUpdate = function() {
	DBRemote.app.rpc.game.remote.getOnlineUser(null,function(users) {
		DBRemote.dbService.dayOnlineUpdate(users)
	})
}
//检查过期房间
local.dayClearRoom = function() {
	var nodeLength = DBRemote.app.getServersByType('gameNode').length
	for(var i = 0;i < nodeLength;i++){
		var params = {}
		params.gid = i
		DBRemote.app.rpc.gameNode.remote.clearRoom(null,params,function(){})
	}
}
//获取排行榜记录
DBRemote.prototype.getRankingRecord = function(gameType,cb) {
	DBRemote.dbService.db.lrange("game:ranking:record:"+gameType,-100,-1,function(err,data) {
		if(!err && data){
			cb(true,data)
		}else{
			cb(true,[])
		}
	})
}

//获取个人记录
DBRemote.prototype.getUserRecord = function(uid,gameType,cb) {
	DBRemote.dbService.db.lrange("game:user:history:"+gameType+":"+uid,-10,-1,function(err,data) {
		if(!err && data){
			cb(true,data)
		}else{
			cb(true,[])
		}
	})
}